<template>
    <div class="views-dingdan-index">
        <div>
            <e-container>
                <div class="title-modelbox-widget1">
                    <h3 class="section-title">创建订单</h3>
                    <div class="sidebar-widget-body">
                        <div class="order-checkout-info">
                            <div class="order-product-list">
                                <div class="order-checkout-title">
                                    <div class="product-item-title">确认商品</div>
                                </div>
                                <div style="margin-bottom: 10px" class="card-list-content">
                                    <div class="card-list-item card-list-item">
                                        <div class="card-info">
                                            <div class="card-info-title">商品</div>
                                        </div>
                                        <div class="card-price">
                                            <div class="card-price-now">价格</div>
                                        </div>
                                        <div class="card-number">
                                            <div class="card-price-now">购买数量</div>
                                        </div>
                                        <div class="card-total">
                                            <div class="card-price-now">小计</div>
                                        </div>
                                    </div>
                                    <div class="card-list-item" v-for="(item) in dataSets" :key="item.id">
                                        <div class="card-info">
                                            <div class="card-img">
                                                <e-img :src="item.tupian" pb="100" />
                                            </div>

                                            <div class="card-content">
                                                <div class="card-title">{{ item.mingcheng }}</div>
                                            </div>
                                        </div>
                                        <div class="card-price">
                                            <div class="card-price-now price">￥{{ item.jiage }}</div>
                                        </div>
                                        <div class="card-number">{{ item.goumaishuliang }}</div>
                                        <div class="card-total price">￥<span class="card-total-span">{{ item.xiaoji }}</span></div>
                                    </div>
                                </div>

                                <div class="order-checkout-title">
                                    <div class="product-item-title">填写订单信息</div>
                                </div>
                                <div class="order-checkout-form">
                                    <el-form :model="form" ref="formModel" label-position="right" label-width="140px" status-icon validate-on-rule-change>
                                        <el-form-item label="备注" prop="beizhu"> <el-input type="textarea" v-model="form.beizhu"></el-input> </el-form-item>
                                    </el-form>
                                </div>

                                <div class="card-bottom-fix">
                                    <div class="card-bottom-box">
                                        <div class="container-box">
                                            <div class="card-bottom-checkout">
                                                <div class="checkout-tips">共计 <i>{{ selectCount }}</i> 件商品，</div>
                                                <div class="checkout-price">
                                                    订单金额：<span class="price">￥<i>{{ orderTotal }}</i></span>
                                                </div>
                                                <a href="javascript:;" class="checkout-button" @click="submitCheckout">创建订单</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- /.sidebar-widget-body -->
                </div>
            </e-container>
        </div>
    </div>
</template>

<script setup>
    import http from "@/utils/ajax/http";
    import DB from "@/utils/db";
    import router from "@/router";
    import rule from "@/utils/rule";

    import { ref, reactive, watch, unref, onBeforeMount, computed } from "vue";
    import { useRoute } from "vue-router";
    import { session } from "@/utils/utils";
    import { canDingdanSelect, useDingdanSelect, canDingdanDelete, useDingdanCreateForm, canDingdanInsert } from "@/module";
    import { extend } from "@/utils/extend";
    import { ElMessageBox, ElMessage } from "element-plus";
    import { extend } from "vue-design-plugin";

    const route = useRoute();
    const search = reactive({
        dingdanbianhao: "",
        page: 1, // 当前页
        pagesize: 12, // 每页行数
        orderby: "id", // 排序字段
        sort: "desc", // 排序类型
    });
    extend(search, route.query);
    // 链接参数变化时更新这些内容
    watch(
        () => route.query,
        () => {
            extend(search, route.query);
            loadList(1);
        },
        { deep: true }
    );

    // 总行数
    const totalCount = ref(0);
    /**
     * 列表数据
     * @type {EDingdan[]}
     */
    const lists = ref([]);
    // 加载状态
    const loading = ref(false);

    // 排序操作
    const sortChange = (e) => {
        console.log(e);
        if (e.order == null) {
            search.orderby = "id";
            search.sort = "desc";
        } else {
            search.orderby = e.prop;
            search.sort = e.order == "ascending" ? "asc" : "desc";
        }
        loadList(1);
    };
    // 设置页数多少
    const sizeChange = (e) => {
        search.pagesize = e;
        loadList(1);
    };

    // 加载订单列表方法
    const loadList = (page) => {
        // 加载
        if (unref(loading)) return;
        loading.value = true;
        search.page = page;

        http.post("/api/dingdan/selectPages", search).then(
            (res) => {
                loading.value = false;
                if (res.code == 0) {
                    var data = res.data;
                    lists.value = data.lists.records;
                    totalCount.value = data.lists.total;
                }
            },
            (err) => {
                loading.value = false;
                ElMessage.error(err.message);
            }
        );
    };

    onBeforeMount(() => {
        loadList(1);
    });
    const props = defineProps({
        btnText: {
            type: String,
            default: "",
        },
        isRead: {
            type: Boolean,
            default: true,
        },
        isHouxu: {
            type: Boolean,
            default: true,
        },
        labelWidth: {
            type: String,
            default: "140px",
        },
    });
    const { form } = useDingdanCreateForm();
    const emit = defineEmits(["success"]);
    const formModel = ref();
    const loading = ref(false);
    var submit = () => {
        return new Promise((resolve, reject) => {
            formModel.value
                .validate()
                .then((res) => {
                    if (loading.value) return;
                    loading.value = true;
                    canDingdanInsert(form).then(
                        (res) => {
                            loading.value = false;
                            if (res.code == 0) {
                                emit("success", res.data);
                                if (props.isHouxu) {
                                    ElMessage.success("添加成功");
                                    formModel.value.resetFields();
                                }
                            } else {
                                ElMessageBox.alert(res.msg);
                            }
                            resolve(res);
                        },
                        (err) => {
                            loading.value = false;
                            ElMessageBox.alert(err.message);
                            reject(err);
                        }
                    );
                })
                .catch((err) => {
                    reject(err);
                });
        });
    };

    const dataSets = ref([]);
    const loaddataSets = async () => {
        if (route.query.liji) {
            dataSets.value = JSON.parse(sessionStorage.getItem("JSON") || "[]");
            form._lijigoumai = "1";
            form._JSON = dataSets.value;
            form._biao = "dingdanshangpin";
        } else {
            dataSets.value = await DB.name("gouwuche").where("goumairen", session("username")).where("id", "in", route.query.ids).order("id desc").select();
        }
    };
    loaddataSets();
    form.targetIds = route.query.ids; // 添加提交值
    const selectCount = computed(() => {
        var tmpList = unref(dataSets);
        var count = 0;
        for (var item of tmpList) {
            count += item.goumaishuliang;
        }
        return count;
    });

    const orderTotal = ref(0);
    watch(
        dataSets,
        () => {
            var tmpList = unref(dataSets);
            var total = 0;
            for (var item of tmpList) {
                total += item.jiage * item.goumaishuliang;
            }
            orderTotal.value = total.toFixed(2);
            form.dingdanjine = total.toFixed(2);
        },
        { deep: true, immediate: true }
    );
    const submitCheckout = () => {
        submit()
            .then((res) => {
                if (res.code == 0) {
                    // 创建订单成功，跳转到支付页面
                    var row = res.data;
                    router.replace({
                        path: "/pay",
                        query: { biao: "dingdan", id: row.id, ordersn: row.dingdanbianhao, zongji: row.dingdanjine, isShaxiang: "", redirect: "/admin/dingdan/xiadanren" },
                    });
                }
            })
            .catch((err) => {});
    };
</script>

<style scoped lang="scss">
    .views-dingdan-index {
    }
</style>
